<!-- 物资领用单 -->
<template>
  <div>
    <cus-search style="min-width: 1200px; padding-bottom: 0">
      <cus-search-item>
        <Form
          :model="form"
          :label-width="80"
          ref="formValidate"
          @keydown.native.enter.prevent="onInit"
        >
          <FormItem label="创建日期" class="mr_48 mb_20">
            <DatePicker
              type="daterange"
              v-model="dateStr"
              ref="formDate"
              @on-change="sDateChange"
              placeholder="开始日期 - 结束日期"
              style="width: 200px"
            />
          </FormItem>
          <FormItem label="领用单号" class="mr_48 mb_20" prop="billNo">
            <Input
              placeholder="请输入领用单号"
              maxlength="20"
              clearable
              v-model="form.billNo"
            />
          </FormItem>
          <cusButton
            class="mr_20 mb_20"
            type="primary"
            @onClick="
              pages.page = 1;
              postApiGoodsReceiveorderListApi();
            "
            >查询</cusButton
          >
          <cusButton class="mr_20 mb_20" type="primary" @onClick="reset()"
            >重置</cusButton
          >
        </Form>
      </cus-search-item>
    </cus-search>
    <cus-card class="cus_cardBox" :showTitle="false">
      <div class="btnBox">
        <cusButton type="primary" @onClick="onCreateRequisition()" style="width: 150px"
          >添加</cusButton
        >
      </div>
      <cusTable
        border
        :loading="form.loading"
        :columns="columns"
        :data="data"
        :size="vuex_config.tableSize"
        :bottomClass="['cus-page']"
      >
        <template slot-scope="{ row }" slot="statusOperation">
          <div style="display: flex; align-items: center; justify-content: center">
            <div
              style="width: 8px; height: 8px; border-radius: 100%; margin-right: 6px"
              :style="{
                background: row.status == 'finished' ? '#03AB5A' : '#666666',
              }"
            ></div>
            <div
              :style="{
                color: row.status == 'finished' ? '#03AB5A' : '#666666',
              }"
            >
              {{
                row.status == "doing"
                  ? "进行中"
                  : row.status == "finished"
                  ? "已完成"
                  : ""
              }}
            </div>
          </div>
        </template>
        <template slot-scope="{ row, index }" slot="operation">
          <div class="flex">
            <cus-button
              type="text"
              size="small"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 8px"
              @onClick="onShow(row)"
            >
              <Icon type="ios-search" size="4" style="margin: 2px 3px 0 0" />
              <span>查看</span>
            </cus-button>
            <cus-button
              type="text"
              size="small"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 8px"
              @onClick="onConfirm(row)"
            >
              <Icon
                type="ios-checkmark-circle-outline"
                size="4"
                v-if="row.checkStatus == 1"
                style="margin: 2px 3px 0 0"
              />
              <span v-if="row.checkStatus == 1">确认领用单</span>
              <Icon
                type="ios-search"
                size="4"
                v-if="row.checkStatus != 1"
                style="margin: 2px 3px 0 0"
              />
              <span v-if="row.checkStatus != 1">查看二维码</span>
            </cus-button>
            <cus-button
              type="text"
              size="small"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 8px"
              @onClick="requisition(row)"
            >
              <Icon type="ios-download-outline" size="4" style="margin: 2px 3px 0 0" />
              <span>物资领用单生成</span>
            </cus-button>
          </div>
        </template>
      </cusTable>
      <div class="cus_page">
        <cus-page
          :data="pages"
          class="mt_20"
          @pageChange="postApiGoodsReceiveorderListApi"
        ></cus-page>
      </div>
    </cus-card>
    <!--物资领用单详情-->
    <materialDetails ref="materialDetails"></materialDetails>
    <!--查看二维码-->
    <Modal
      v-model="modal"
      title="二维码"
      ok-text="下载二维码"
      @on-ok="ok"
      width="800"
      @on-cancel="modal = false"
    >
      <div
        style="
          display: flex;
          flex-flow: row wrap;
          justify-content: center;
          max-height: 410px;
          overflow: auto;
        "
      >
        <div class="mr_20" v-for="(item, index) in qcode" :key="index">
          <viewer ref="viewer" :images="[item]" style="z-index: 99999">
            <img :src="item" style="height: 200px; width: 200px" />
          </viewer>
        </div>
      </div>
      <div class="flex" style="color: red; margin-top: 48px">
        * 提示：请选择二维码放大之后在进行扫码。
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  postApiGoodsReceiveorderList,
  getApiPurchasingExportSummaryList,
  postApiReceiveorderCheckstatus,
  postApiGoodsRriceiveorderQrcode,
  getApiGoodsHandaworkItem,
} from "@/api/business/manager";
import materialDetails from "./components/materialDetails.vue";
import axios from "axios";
import moment from "moment";
// require 方式
require("moment/locale/zh-cn");
moment.locale("zh-cn", {
  week: {
    dow: 1,
  },
});
// import 方式
import "moment/locale/zh-cn";
moment.locale("zh-cn");

export default {
  components: { materialDetails },
  data() {
    return {
      form: {
        startDate: "", //开始时间
        stopDate: "", //结束时间
        billNo: "", //领用单号
        loading: false,
      },
      ruleValidate: {}, //rule验证
      dateStr: [], //默认一周"开始-结束"时间
      refresh: false,
      columns: [
        {
          title: "序号",
          type: "index",
          align: "center",
          width: 70,
        },
        {
          title: "领用单号",
          key: "billNo",
          minWidth: 125,
          align: "center",
        },
        {
          title: "领用单位",
          key: "recipientDepartmentName",
          minWidth: 125,
          align: "center",
        },
        {
          title: "物资数量",
          key: "goodsNum",
          minWidth: 125,
          align: "center",
        },
        {
          title: "确认状态",
          key: "checkStatus",
          minWidth: 175,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                {
                  style: {
                    background:
                      params.row.checkStatus == 1
                        ? "#ED4014"
                        : params.row.checkStatus == 2
                        ? "#19BE6B"
                        : "#FF9900",
                    color: "#FFFFFF",
                    padding: "5px",
                  },
                },
                params.row.checkStatus == 1
                  ? "未确认"
                  : params.row.checkStatus == 2
                  ? "已领取"
                  : "已确认"
              ),
            ]);
          },
        },
        {
          title: "创建时间",
          key: "createTime",
          minWidth: 175,
          align: "center",
        },
        {
          title: "操作",
          fixed: "right", // 右侧固定
          slot: "operation",
          align: "center",
          width: 285,
        },
      ],
      data: [], // 表格列表
      modal: false, //查二维码弹框
      qcode: [], //二位码
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0,
      },
    };
  },
  mounted() {
    this.getCurrentWeek();
    this.onInit();
  },
  activated() {
    this.postApiGoodsReceiveorderListApi();
  },
  methods: {
    onInit() {
      this.postApiGoodsReceiveorderListApi();
    },
    reset() {
      this.$refs.formDate.handleClear();
      this.$refs["formValidate"].resetFields();
    },
    // 创建领用单跳转
    onCreateRequisition() {
      this.$router.push({
        path: "/createRequisition/createRequisition",
        query: {},
      });
    },
    // 时间事件
    sDateChange(time) {
      this.form.startDate = time[0];
      this.form.stopDate = time[1];
      this.postApiGoodsReceiveorderListApi();
    },
    // 查看物资领用单详情
    onShow(row) {
     
      this.$refs["materialDetails"].show(row.id);
    },
    // 确认领用单
    onConfirm(row) {
      if (row.checkStatus == 1) {
        this.$cu
          .dialog({
            title: "提示",
            content: "是否要确认领用单：单号（" + row.billNo + ")",
          })
          .then(() => {
            this.postApiReceiveorderCheckstatusApi(row.id);
          });
      } else {
        this.modal = true;
        this.postApiGoodsRriceiveorderQrcodeApi(row.id);
      }
    },
    // 物资领用单生成按钮
    requisition(row) {
      console.log(row);
      window.location.href = `${getApiPurchasingExportSummaryList(row.id)}&token=${
        this.$store.state.vuex_user.token
      }`;
    },
    // 下载二维码
    ok() {
      this.qcode.forEach((element) => {
        console.log(element);
        this.downloadUrlFile(element);
      });
    },
    // 创建跨域请求
    async getImage(url) {
      console.log(url,11111);
      const { data } = await axios({
        method: "GET",
        url:  url,
        responseType: "blob",
      });
      return data;
    },
    // 获取链接后的地址
    GetUrlRelativePath(url) {
      console.log(url);
      var arrUrl = url.split("//");
      var start = arrUrl[1].indexOf("/");
      var relUrl = arrUrl[1].substring(start); //stop省略，截取从start开始到结尾的所有字符
      if (relUrl.indexOf("?") != -1) {
        relUrl = relUrl.split("?")[0];
      }
      return relUrl;
    },
    downloadUrlFile(file, fileName = new Date().valueOf()) {
      let url = this.GetUrlRelativePath(file);
      this.getImage(url).then((res) => {
        console.log(res);
        const myBlob = new Blob([res], { type: "image/jpeg" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(myBlob);
        link.download = fileName;
        link.click();
        link.remove();
        URL.revokeObjectURL(link.href);
      });
    },
    getCurrentWeek() {
      let start = moment().weekday(0).format("YYYY-MM-DD"); //本周一
      let end = moment().weekday(6).format("YYYY-MM-DD"); //本周日
      // this.dateStr[0] = start; //默认一周开始时间
      // this.dateStr[1] = end; //默认一周结束时间
      this.form.startDate = start;
      this.form.stopDate = end;
                  // 数组更新需要使用$set手动更新
                  this.$set(this.dateStr,0,start)
      this.$set(this.dateStr,1,end)
   
    },
    // 物资领用单------------------------接口
    postApiGoodsReceiveorderListApi() {
      return new Promise((resolve) => {
        let params = {
          startDate: this.form.startDate, //开始时间
          stopDate: this.form.stopDate, //结束时间
          billNo: this.form.billNo, //领用单号
          current: this.pages.page,
          size: this.pages.pageSize,
        };
        postApiGoodsReceiveorderList(params).then((res) => {
          this.$cu.hideLoading();
          if (res.retCode === 2000) {
            res.data.records.forEach((element) => {
              element.flag = true;
            });
            this.data = res.data.records;
            this.pages.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    // 确认领用单-------------------------接口
    postApiReceiveorderCheckstatusApi(id) {
      return new Promise((resolve) => {
        let params = {
          id: id,
        };
        postApiReceiveorderCheckstatus(params).then((res) => {
          if (res.retCode === 2000) {
            this.$Message.success(res.retMsg);
            this.postApiGoodsReceiveorderListApi();
            resolve();
          }
        });
      });
    },
    // 获取二维码---------------------接口
    postApiGoodsRriceiveorderQrcodeApi(id) {
      return new Promise((resolve) => {
        let params = {
          receiveOrderId: id,
        };
        postApiGoodsRriceiveorderQrcode(params).then((res) => {
          if (res.retCode === 2000) {
            this.qcode = res.data;
            resolve();
          }
        });
      });
    },
    // 获取物资物资种类-----------------接口
    getApiGoodsHandaworkItemApi() {
      return new Promise((resolve) => {
        getApiGoodsHandaworkItem().then((res) => {
          if (res.retCode === 2000) {
            let obj = {
              name: "全部",
            };
            res.data.unshift(obj);
            this.productClassTree = res.data;
            resolve();
          }
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.btnBox {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
::-webkit-scrollbar {
  width: 10px;

  height: 10px;

  background-color: #f5f5f5;
}

/*定义滚动条轨道

内阴影+圆角*/

::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.8);

  border-radius: 10px;

  background-color: #f5f5f5;
}

/*定义滑块

内阴影+圆角*/

::-webkit-scrollbar-thumb {
  border-radius: 10px;

  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);

  background-color: #555;
}
</style>
